const { request } = require('../../../utils/request');

Page({
  data: {
    searchKeyword: '',
    hotProducts: [],
    searchResults: [],
    searched: false
  },

  onLoad() {
    this.fetchHotProducts();
  },

  // 获取热卖商品数据
  fetchHotProducts() {
    request({
      url: '/product',
      method: 'GET',
      data: {
        is_hot: true,
        page_size: 3
      },
      showLoading: true
    })
    .then((res) => {
      if (res.code === 2000) {
        this.setData({
          hotProducts: res.data.items
        });
      }
    })
    .catch((error) => {
      console.error('获取热卖商品数据失败:', error);
    });
  },

  // 输入框输入事件处理
  onInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 执行搜索操作
  searchProducts() {
    const keyword = this.data.searchKeyword.trim();
    if (!keyword) {
      wx.showToast({
        title: '请输入搜索关键词',
        icon: 'none'
      });
      return;
    }

    request({
      url: '/product',
      method: 'GET',
      data: {
        search_keyword: keyword
      },
      showLoading: true
    })
    .then((res) => {
      if (res.code === 2000) {
        this.setData({
          searchResults: res.data.items,
          searched: true
        });
      }
    })
    .catch((error) => {
      console.error('搜索商品失败:', error);
      this.setData({
        searchResults: [],
        searched: true
      });
    });
  }
});